package com.my.mymafengwo.activity;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.widget.FrameLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;

import com.example.smallstrong.mafengwopro.R;
import com.my.mymafengwo.base.BaseActivity;
import com.my.mymafengwo.fragment.DiscoverFragment;
import com.my.mymafengwo.fragment.LocalFragment;
import com.my.mymafengwo.fragment.MineFragment;

import java.util.ArrayList;
import java.util.List;


public class MainActivity extends BaseActivity implements RadioGroup.OnCheckedChangeListener {
    /**
     * 主界面下方选择按钮
     */
    private RadioGroup rg;
    private FrameLayout frameLayout;
    private List<Fragment> fragmentList;


    @Override
    protected void loadXml() {
        setContentView(R.layout.activity_main);
    }

    @Override
    protected void getIntentData(Bundle savedInstanceState) {

    }

    @Override
    protected void initViews() {

        rg = (RadioGroup) findViewById(R.id.rg_main);
        frameLayout = (FrameLayout) findViewById(R.id.fl_main);
    }

    @Override
    protected void registerListener() {
        rg.setOnCheckedChangeListener(this);
        rg.check(R.id.rbtn_discover);
    }

    @Override
    protected void initData() {
        fragmentList = new ArrayList<>();
        fragmentList.add(new DiscoverFragment());
        fragmentList.add(new LocalFragment());
        fragmentList.add(new MineFragment());
    }

    /**
     * 选择改变的监听
     *
     * @param group
     * @param checkedId
     */
    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        RadioButton rbtn = (RadioButton) rg.findViewById(checkedId);
        int tag = Integer.parseInt(rbtn.getTag().toString());

        Fragment fragment = (Fragment) adapter.instantiateItem(frameLayout, tag);
        adapter.setPrimaryItem(frameLayout, 0, fragment);
        adapter.finishUpdate(frameLayout);
    }

    /**
     * Fragment的适配器
     */
    FragmentStatePagerAdapter adapter = new FragmentStatePagerAdapter(getSupportFragmentManager()) {
        @Override
        public Fragment getItem(int position) {
            return fragmentList == null || fragmentList.size() == 0 ? null : fragmentList.get(position);
        }

        @Override
        public int getCount() {
            return fragmentList == null ? 0 : fragmentList.size();
        }
    };
}
